//道具类
import Sprite from './base/sprite'
import DataBus from './databus'

const NOMAL_IMG_SRC = 'images/a_run.png'
const RE_TIME_INTERVAL = 60

let databus = new DataBus()

//方块图片集合 - 种类
const PROP_IMGS = ['images/a_run.png', 'images/clock.png', 'images/s_horizontal.png', 'images/bomb.png', 'images/eye_miss.png', 'images/a_down.png', 'images/diamond.png', 'images/lock.png', 'images/lock.png', 'images/lock.png']

export default class DPropItem extends Sprite {
  constructor(x, y, w, h, p) {
    super(NOMAL_IMG_SRC, x, y, w, h)

    // 1.加速器(a_run操作控制加速)
    // 2.计时器(clock倒计时未消除即结束)
    // 3.混乱控制(s_horizontal左右不受控制)
    // 4.炸弹(bomb随机消除已存在的一行)
    // 5.蒙面(eye_miss运行中不可见)
    // 6.下落速度加快(a_down) 
    // 7.钻石(diamond获得额外钻石)
    // 8.操作锁定(lock操作不允许执行: 左)
    // 9.操作锁定(lock操作不允许执行: 旋转)
    // 10.操作锁定(lock操作不允许执行: 右)
    this.p = p //默认值

    this.visible = false

    this.time_show = 1000 //道具展示最长时间
    this.time_store = 1000 //道具效果时间

    this.re_init_time = 0
    this.last_init_time_store = 0 - RE_TIME_INTERVAL

    this.time_end = Date.now() + 1000 * 60 *1 //1分钟
  }
  //复用时重置属性值
  reInit() {

    if (this.re_init_time - this.last_init_time_store < RE_TIME_INTERVAL)     {
      return;
    }
    this.last_init_time_store = this.re_init_time + RE_TIME_INTERVAL;

    //随机一个道具
    let p = Math.floor(Math.random() * PROP_IMGS.length)

    if (databus.time_in) {//如果在倒计时时间内有1/3概率获得炸弹
      let t = Math.floor(Math.random() * 3)
      if (t === 0) {
        p = 3
      }
    }

    this.img.src = PROP_IMGS[p]
    this.p = p + 1

    let item_rect = this.judgeLocation();

    if (item_rect.length) {

      this.sendProp(item_rect)
    }
  }

  //判断位置
  judgeLocation() {

    if (databus.floor_diamonds_judge.length > 10){
      let random_index = Math.floor(Math.random() * 10)
      let item_rect_str = databus.floor_diamonds_judge[random_index];
      let item_rect = item_rect_str.split(',');
      item_rect[1] -= 4;
      let isLoacation = databus.isCanLocationItem(item_rect);
      if (isLoacation) {

        return item_rect
      }
    }
    return []
  }
  //设置位置发道具
  sendProp(item_rect){

    this.x = parseInt(item_rect[0]);
    this.y = parseInt(item_rect[1]);
    this.w = parseInt(item_rect[2]);
    this.h = parseInt(item_rect[3]);
    this.time_show = 1000
    this.visible = true
  }

  update(){

    this.re_init_time ++;
    if(this.time_show >= 0) {
      this.time_show--;
      if (this.time_show <= 0) {
        // console.log('道具时间到' + this.p)
        this.visible = false
      }
    }
    
    if (this.time_store >= 0 && databus.propState !== 0){
      this.time_store--;
      // console.log(this.p + '道具时间剩余时间' + this.time_store)
      if (this.time_store <= 0) {

        databus.propState = 0
      }
    }
  }
}